﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using QWManage.DAL;
using QWManage.Model;
using QWManage.Utils;
using System;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace QWManage.MySqlSync
{
    public partial class FrmSynchoronousMySql : Form
    {
        private Thread _thread;
        string _new_sql_table_name = "ECO_Member";
        public FrmSynchoronousMySql()
        {
            InitializeComponent();
        }

        private void FrmSynchoronousMySql_Load(object sender, EventArgs e)
        {
            this.FormClosing += FrmSynchoronousMySql_FormClosing;

            MysqlSyncCfgInfo cfg = MysqlSyncCfgMgr.Get();
            setParameters(cfg);
        }
        private void setParameters(MysqlSyncCfgInfo cfg)
        {
            txtServer.Text = cfg.MysqlServer;
            txtUser.Text = cfg.MysqlUser;
            txtDataBase.Text = cfg.MysqlDataBase;
            txtMySqlPassword.Text = cfg.MysqlPassword;
            txtPort.Text = cfg.MysqlPort;
            txtOwner.Text = cfg.Owner;

            txtDataSource.Text = cfg.MssqlDataSource;
            txtInitialCatalog.Text = cfg.MssqlInitialCatalog;
            txtUserID.Text = cfg.MssqlUserID;
            txtPassword.Text = cfg.MssqlPassword;
        }
        private MysqlSyncCfgInfo saveConfig()
        {
            MysqlSyncCfgInfo cfg = new MysqlSyncCfgInfo();
            cfg.MysqlServer = txtServer.Text.Trim(); ;
            cfg.MysqlUser = txtUser.Text.Trim();
            cfg.MysqlDataBase = txtDataBase.Text.Trim();
            cfg.MysqlPassword = txtMySqlPassword.Text.Trim(); ;
            cfg.MysqlPort = txtPort.Text.Trim();
            cfg.Owner = txtOwner.Text.Trim();

            cfg.MssqlDataSource = txtDataSource.Text.Trim();
            cfg.MssqlInitialCatalog = txtInitialCatalog.Text.Trim(); ;
            cfg.MssqlUserID = txtUserID.Text.Trim(); ;
            cfg.MssqlPassword = txtPassword.Text.Trim();
            MysqlSyncCfgMgr.Set(cfg);
            return cfg;
        }

        private void FrmSynchoronousMySql_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null && _thread.IsAlive) _thread.Abort();
        }

        private void btnSqlDBConnect_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                string conn_str = getMssqlConnStr();
                try
                {
                    using (SqlConnection conn = new SqlConnection(conn_str))
                    {
                        conn.Open();
                        conn.Close();
                        Common.MessageBoxInformation("Sql Server数据连接测试成功。");
                    }
                }
                catch (Exception temp_ex)
                {
                    Common.MessageBoxWarning("Sql Server数据连接测试失败：" + temp_ex.Message);
                }

            }
            catch (Exception ex)
            {
                Common.MessageBoxWarning(ex.Message);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            string cfg_path = Path.Combine(Application.StartupPath, "CFGS");
            if (!Directory.Exists(cfg_path))
            {
                Directory.CreateDirectory(cfg_path);
            }
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "配制文件(*.cfg)|*.cfg";
            dlg.InitialDirectory = cfg_path;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string json = File.ReadAllText(dlg.FileName, System.Text.Encoding.UTF8);
                AppConfigInfo appConfigInfo = JsonConvert.DeserializeObject<AppConfigInfo>(json);
                txtDataSource.Text = appConfigInfo.DataSource;
                txtInitialCatalog.Text = appConfigInfo.InitialCatalog;
                txtUserID.Text = appConfigInfo.UserID;
                txtPassword.Text = appConfigInfo.Password;
            }
        }

        private void btnMySqlDBConnect_Click(object sender, EventArgs e)
        {

            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                string conn_str = getMysqlConnStr();
                try
                {
                    using (MySqlConnection conn = new MySqlConnection(conn_str))
                    {
                        conn.Open();
                        conn.Close();
                        Common.MessageBoxInformation("MySql数据连接测试成功。");
                    }
                }
                catch (Exception temp_ex)
                {
                    Common.MessageBoxWarning("MySql数据连接测试失败：" + temp_ex.Message);
                }
            }
            catch (Exception ex)
            {
                Common.MessageBoxWarning(ex.Message);
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private string getMssqlConnStr()
        {
            string mssql_conn_str = $"" +
                  $"Data Source={txtDataSource.Text.Trim()};" +
                  $"Initial Catalog={txtInitialCatalog.Text.Trim()};" +
                  $"User ID={txtUserID.Text.Trim()};" +
                  $"Password={txtPassword.Text.Trim()};";

            return mssql_conn_str;
        }

        private string getMysqlConnStr()
        {
            string mysql_conn_str = "" +
            $"server={txtServer.Text.Trim()};" +
            $"user={txtUser.Text.Trim()};" +
            $"database={txtDataBase.Text.Trim()};" +
            $"port={txtPort.Text.Trim()};" +
            $"password={txtMySqlPassword.Text.Trim()}";
            return mysql_conn_str;
        }

        private void btnCreateTable_Click(object sender, EventArgs e)
        {
            saveConfig();
            string mysql_conn_str = getMysqlConnStr();
            string mssql_conn_str = getMssqlConnStr();

            string create_table_sql = MySqlToSqlServerConverter.GetCreateTableSql(mysql_conn_str, "member", _new_sql_table_name);

            using (SqlConnection sqlconn = new SqlConnection(mssql_conn_str))
            {
                sqlconn.Open();

                string drop_table_sql = $"DROP TABLE IF EXISTS [dbo].{_new_sql_table_name}";

                SqlCommand sqlCommand_drop = new SqlCommand(drop_table_sql, sqlconn);
                sqlCommand_drop.ExecuteNonQuery();

                SqlCommand sqlCommand_create = new SqlCommand(create_table_sql, sqlconn);
                sqlCommand_create.ExecuteNonQuery();
            }
            MessageBox.Show("创建表格成功");
        }

        private void workService()
        {
            try
            {
                foreach (Control control in this.Controls) { control.Enabled = false; }
                progressBar.Enabled = true;
                this.Cursor = Cursors.WaitCursor;
                string mysql_conn_str = getMysqlConnStr();
                string mssql_conn_str = getMssqlConnStr();
                string owner = txtOwner.Text.Trim();
                MySqlDAL.Synchoronous(owner, mysql_conn_str, mssql_conn_str, progressBar);
                new UpdateLogsDAL().Log("ECO数据同步", owner);
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        MessageBox.Show("同步完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }));
                }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) { control.Enabled = true; }
                this.Cursor = Cursors.Default;
            }
        }

        private void btnStartSync_Click(object sender, EventArgs e)
        {
            saveConfig();
            _thread = new Thread(new ThreadStart(workService));
            _thread.Start();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            string sql_conn_str = $"" +
                 $"Data Source={txtDataSource.Text.Trim()};" +
                 $"Initial Catalog={txtInitialCatalog.Text.Trim()};" +
                 $"User ID={txtUserID.Text.Trim()};" +
                 $"Password={txtPassword.Text.Trim()};";

            using (SqlConnection sqlconn = new SqlConnection(sql_conn_str))
            {
                sqlconn.Open();
                string sql = $"truncate table {_new_sql_table_name}";
                SqlCommand cmd = new SqlCommand(sql, sqlconn);
                cmd.ExecuteNonQuery();
            }

        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            MysqlSyncCfgInfo cfgInfo = saveConfig();
            string json = JsonConvert.SerializeObject(cfgInfo);
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "配制文件(*.cfg)|*.cfg";
            dlg.DefaultExt = "cfg";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(dlg.FileName, json, Encoding.UTF8);
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "配制文件(*.cfg)|*.cfg";
            dlg.DefaultExt = "cfg";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string json = File.ReadAllText(dlg.FileName, Encoding.UTF8);
                MysqlSyncCfgInfo cfg = JsonConvert.DeserializeObject<MysqlSyncCfgInfo>(json);
                setParameters(cfg);
            }
        }
    }
}
